<template>
  <div class="container">
    <el-row>
      <el-col :span="24" align="right" v-if="!tableData.length">
        <el-button type="primary" @click="increase">{{$t('m.add')}}</el-button>
      </el-col>
    </el-row>
    <el-table
      ref="table"
      stripe
      empty-text
      fits
      class="table-wrap single-select-table"
      :data="tableData"
      :row-style="tableRowStyle"
      :row-class-name="tableRowClassName"
      @row-click="rowClick"
      @selection-change="handleSingleSelectionChange">
      <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
      <el-table-column align="center" prop="orderno" :label="$t('m.sortNumber')" width="100"></el-table-column>
      <el-table-column align="center" prop="warehousename" :label="$t('m.page.warehouse')+$t('m.name')"></el-table-column>
      <el-table-column :label="$t('m.state')" width="100" align="center">
        <template slot-scope="scope">{{scope.row.state?'已启用':'已停用'}}</template>
      </el-table-column>
      <el-table-column align="center" prop="remark" :label="$t('m.remark')"></el-table-column>
      <el-table-column align="center" prop="creator" :label="$t('m.creator')"></el-table-column>
      <el-table-column align="center" prop="createdate" :label="$t('m.createdate')"></el-table-column>
      <el-table-column align="center" prop="modifier" :label="$t('m.modifier')"></el-table-column>
      <el-table-column align="center" prop="modifydate" :label="$t('m.modifydate')"></el-table-column>

      <el-table-column :label="$t('m.operation')" width="180" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state==1"
            type="primary"
            @click="open(scope.row, '编辑', 'edit', true)"
            size="mini"
          >{{$t('m.edit')}}</el-button>
          <el-button
            type="primary"
            v-if="scope.row.state==0"
            size="mini"
            @click="handleState1(scope.$index, scope.row)"
          >{{$t('m.start')}}</el-button>
          <el-button
            type="primary"
            v-if="scope.row.state==1"
            size="mini"
            @click="handleState2(scope.$index, scope.row)"
          >{{$t('m.stop')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @current-change="currentChange"
      style="margin-top:20px"
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :current-page="currentPage"
      :total="total"
    ></el-pagination>

    <!-- 仓库编辑 dialog 开始 -->
    <el-dialog
      :close-on-click-modal="false"
      @close="closeDialog"
      width="600px"
      :title="$t('m.edit')"
      :visible.sync="dialogFormVisible"
    >
      <el-form :rules="ruleFormEdit" ref="ruleFormEdit" size="mini" :model="form">
        <el-form-item :label="$t('m.page.warehouse')+$t('m.name')" :label-width="formLabelWidth" prop="warehousename">
          <el-input size="mini" v-model="form.warehousename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('m.state')" :label-width="formLabelWidth" align="left">
          <template>
            <el-select v-model="stateValue" @change="setState">
              <el-option
                v-for="item in state"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item :label="$t('m.sortNumber')" :label-width="formLabelWidth" prop="orderno">
          <el-input @input="validateNumber2('orderno')"  maxlength="3" show-word-limit size="mini" v-model="form.orderno" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('m.address')" :label-width="formLabelWidth" align="left">
          <template>
            <el-select
              @change="getProvince"
              v-model="form.countryname"
              :placeholder="$t('m.choose')"
              class="w100"
            >
              <el-option
                v-for="(item,index) in conuntryList"
                :key="index"
                :label="item.countryname"
                :value="item.countryid"
              ></el-option>
            </el-select>
            <el-select
              @change="getCity"
              v-model="form.provincename"
              :placeholder="$t('m.choose')"
              class="w100"
            >
              <el-option
                v-for="(item,index) in provinceValue"
                :key="index"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-select
              @change="getArea"
              v-model="form.cityname"
              :placeholder="$t('m.choose')"
              class="w100"
            >
              <el-option
                v-for="(item,index) in cityValue"
                :key="index"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-select
              @change="areaClick"
              v-model="form.areaname"
              :placeholder="$t('m.choose')"
              class="w100 last"
            >
              <el-option
                v-for="(item,index) in areaValue"
                :key="index"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-input size="mini" v-model="form.detailedaddress" autocomplete="off"></el-input>
          </template>
        </el-form-item>

        <el-form-item :label="$t('m.remark')" :label-width="formLabelWidth" prop="remark">
          <el-input
            type="textarea"
            maxlength="100"
            show-word-limit
            v-model="form.remark"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="btns">
        <el-button size="mini" @click="editCancel">{{$t('m.cancel')}}</el-button>
        <el-button size="mini" type="primary" @click="change()">{{$t('m.confirm')}}</el-button>
      </div>
    </el-dialog>
    <!-- 仓库编辑 dialog 结束 -->

    <!-- 仓库新增 dialog 开始 -->
    <el-dialog
      :close-on-click-modal="false"
      @close="closeAddDialog"
      width="600px"
      :title="$t('m.add')"
      :visible.sync="dialogFormVisible1"
    >
      <el-form :rules="ruleFormAdd" ref="ruleFormAdd" size="mini" :model="increaseForm">
        <el-form-item :label="$t('m.page.warehouse')+$t('m.name')" :label-width="formLabelWidth" prop="warehousename">
          <el-input size="mini" v-model="increaseForm.warehousename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('m.state')"
          :label-width="formLabelWidth"
          prop="state"
          align="left"
        >
          <el-select v-model="increaseForm.state" :placeholder="$t('m.choose')">
            <el-option
              v-for="item in state"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('m.sortNumber')" :label-width="formLabelWidth" prop="orderno">
          <el-input @input="validateNumber('orderno')" maxlength="3" show-word-limit size="mini" v-model="increaseForm.orderno" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item :label="$t('m.address')" :label-width="formLabelWidth" align="left" prop="countryid">
          <template>
            <el-select
              @change="getProvince"
              v-model="increaseForm.countryid"
              :placeholder="$t('m.choose')"
              class="w100"
            >
              <el-option
                v-for="(item,index) in conuntryList"
                :key="index"
                :label="item.countryname"
                :value="item.countryid"
              ></el-option>
            </el-select>
            <el-select
              @change="getCity"
              v-model="increaseForm.provincename"
              :placeholder="$t('m.choose')"
              class="w100"
            >
              <el-option
                v-for="(item,index) in provinceValue"
                :key="index"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-select
              @change="getArea"
              v-model="increaseForm.cityname"
              :placeholder="$t('m.choose')"
              class="w100"
            >
              <el-option
                v-for="(item,index) in cityValue"
                :key="index"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-select
              @change="areaClick"
              v-model="form.areaname"
              :placeholder="$t('m.choose')"
              class="w100 last"
            >
              <el-option
                v-for="(item,index) in areaValue"
                :key="index"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-input size="mini" v-model="increaseForm.detailedaddress" autocomplete="off"></el-input>
          </template>
        </el-form-item>

        <el-form-item :label="$t('m.remark')" :label-width="formLabelWidth" prop="remark">
          <el-input
            type="textarea"
            maxlength="100"
            show-word-limit
            v-model="increaseForm.remark"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="btns">
        <el-button size="mini" @click="dialogFormVisible1 = false">{{$t('m.cancel')}}</el-button>
        <el-button size="mini" type="primary" @click="handIncrease()">{{$t('m.confirm')}}</el-button>
      </div>
    </el-dialog>
    <!-- 仓库新增 dialog 结束 -->
  </div>
</template>

<script>
import common from '@/utils/common'

export default {
  name:'warehouse',

  data(){
    return {
      province:[
        {
          value:'area1',
          label:'area1'
        },
        {
          value:'area2',
          label:'area2'
        }
      ],
      provinceAll:[],
      cityAll:[],
      areaAll:[],
      area:[
        {
          value:'area1',
          label:'area1'
        },
        {
          value:'area2',
          label:'area2'
        }
      ],
      stateValue:'',
      conuntryValue:[],
      provinceValue:[],
      cityValue:[],
      areaValue:[],
      status_loading:false,
      formInline:{
        user:''
      },
      tableData:[],
      total:0, //总条数
      pageSize:10, //每页显示条数
      currentPage:1,
      dialogFormVisible:false,
      dialogFormVisible1:false,
      ruleFormAdd:{
        warehousename:[
          { required:true, message:'请输入仓库名称', trigger:'blur' }
        ],
        state:[{ required:true, message:'请选择状态', trigger:'change' }],
        orderno:[{ required:true, message:'请输入排序号', trigger:'blur' }],
        countryid:[
          {
            required:true,
            message:'请选择国家',
            trigger:'change'
          }
        ]
      },
      ruleFormEdit:{
        warehousename:[
          { required:true, message:'请输入仓库名称', trigger:'blur' }
        ],
        state:[{ required:true, message:'请选择状态', trigger:'change' }],
        orderno:[{ required:true, message:'请输入排序号', trigger:'blur' }]
      },
      form:{
        countryname:'',
        countryid:'',
        areaid:0,
        areaname:'',
        cityid:0,
        cityname:'',
        currentPage:0,
        detailedaddress:'',
        orderno:0,
        pageSize:0,
        partitionnumber:0,
        provinceid:0,
        provincename:'',
        remark:'',
        state:'0',
        warehousecode:'',
        warehouseid:0,
        warehousename:''
      },
      increaseForm:{
        countryname:'',
        countryid:'',
        areaid:0,
        areaname:'',
        cityid:0,
        cityname:'',
        currentPage:0,
        detailedaddress:'',
        orderno:null,
        pageSize:0,
        partitionnumber:0,
        provinceid:0,
        provincename:'',
        remark:'',
        state:'0',
        warehousecode:'',
        warehousename:''
      },
      formLabelWidth:'120px',
      conuntryList:[], //存放国家列表
      countryId:null,
      provinceId:null,
      cityId:null,
      statePlaceholder:''
    }
  },
  computed:{
    name(){
      return this.formInline.user
    },

    state(){
      return[
        {
          value:'0',
          label:this.$t('m.stop')
        },
        {
          value:'1',
          label:this.$t('m.start')
        }
      ]
    }
  },
  watch:{

    dialogFormVisible1(){
      let pageSize = this.pageSize

      let currentPage = this.currentPage
      this.inCheckList = []
      this.increaseForm = {
        countryname:'',
        countryid:'',
        areaid:0,
        areaname:'',
        cityid:0,
        cityname:'',
        currentPage:0,
        detailedaddress:'',
        orderno:null,
        pageSize:0,
        partitionnumber:0,
        provinceid:0,
        provincename:'',
        remark:'',
        state:'',
        warehousecode:'',
        warehousename:''
      }
      this.init(currentPage, pageSize)
    }
  },
  methods:{
    validateNumber(key){
      this.$set(this.increaseForm,key,this.increaseForm[key].replace(/[^\d]/g,''))
    },
    validateNumber2(key){
      this.$set(this.form,key,this.form[key].replace(/[^\d]/g,''))
    },
    search(){
      let pageSize = this.pageSize

      let currentPage = this.currentPage

      this.init(currentPage, pageSize)
    },
    handleClick(row){
      const $table = this.$refs.table

      $table.toggleRowExpansion(row)
      $table.toggleRowSelection(row)
    },
    currentChange(page){
      let pageSize = this.pageSize
      let currentPage = page
      this.currentPage = currentPage
      this.init(currentPage, pageSize)
    },
    handleState1(index, row){
      this.tableData[index].state = 1
      this.changeStatus1(index, row)
    },
    handleState2(index, row){
      this.tableData[index].state = 0
      this.changeStatus2(index, row)
    },
    initAddress(id){
      this.provinceValue = []
      let that = this
      that
        .$axios({
          method:'get',
          url:`/region/${id}/tree`
        })
        .then(({data})=> {
          that.provinceAll = data
          for (let i = 0; i < data.length; i++){
            that.provinceValue.push({
              id:data[i].id,
              label:data[i].regionname
            })
          }
          that.initCity()
          that.initArea(that.cityId)
        })
    },
    initCity(){
      this.cityValue = []
      let arr = []
      // for (let i = 0; i < that.provinceAll.length; i++){
      //   let cityItem = that.provinceAll[i].childrens.filter(function(item){
      //     if (item.parentId === id){
      //       arr.push(item)
      //     }
      //   })
      // }
      this.cityAll = arr
      for (let i = 0; i < this.cityAll.length; i++){
        this.cityValue.push({
          id:this.cityAll[i].id,
          label:this.cityAll[i].regionname
        })
      }
    },
    initArea(id){
      this.areaValue = []
      let arr = []
      for (let i = 0; i < this.cityAll.length; i++){
        this.cityAll[i].childrens.filter(function(item){
          if (item.parentId === id){
            arr.push(item)
          }
        })
      }
      this.areaAll = arr
      //console.log( this.areaAll);
      for (let i = 0; i < this.areaAll.length; i++){
        this.areaValue.push({
          id:this.areaAll[i].id,
          label:this.areaAll[i].regionname
        })
      }
    },
    getProvince(id){

      this.form.countryname = this.conuntryList.filter(function(item){
        return item.countryid === id
      })[0].countryname

      //匹配得出一个数组，并且长度为1
      this.form.countryid = id
      this.increaseForm.countryname = this.form.countryname
      this.increaseForm.countryid = id
      this.provinceValue = []
      if (this.countryId !== id){
        this.form.provincename = ''
        this.form.cityname = ''
        this.form.areaname = ''
        this.increaseForm.provincename = ''
        this.increaseForm.cityname = ''
        this.increaseForm.areaname = ''
        this.cityValue = []
        this.areaValue = []
        let that = this

        that
          .$axios({
            method:'get',
            url:`/region/${id}/tree`
          })
          .then(({data})=> {
            that.provinceAll = data
            for (let i = 0; i < data.length; i++){
              that.provinceValue.push({
                id:data[i].id,
                label:data[i].regionname
              })
            }
          })
        this.countryId = id
      }
    },
    getCity(id){
      //1.把province的id和name保存在form中
      //2.通过province的id与cityAll的parentId匹配获取city list
      this.form.provincename = this.provinceValue.filter(function(item){
        return item.id === id
      })[0].label
      //console.log(this.form.provincename);
      this.form.provinceid = id
      this.increaseForm.provincename = this.form.provincename
      this.increaseForm.provinceid = id
      if (this.cityId !== id){
        this.form.cityname = ''
        this.form.areaname = ''
        this.increaseForm.cityname = ''
        this.increaseForm.areaname = ''
        this.areaValue = []
        this.initCity()
        this.cityId = id
      }
      //console.log(this.provinceAll);

      // 这里的id是点击省获得省的id
    },
    getArea(id){
      this.form.cityname = this.cityValue.filter(function(item){
        return item.id === id
      })[0].label
      //console.log(this.form.provincename);
      this.form.cityid = id
      this.increaseForm.cityname = this.form.cityname
      this.increaseForm.cityid = id
      if (this.areaId !== id){
        this.form.areaname = ''
        this.increaseForm.areaname = ''
        this.initArea(id)
        this.areaId = id
      }
    },
    areaClick(id){
      this.form.areaname = this.areaValue.filter(function(item){
        return item.id === id
      })[0].label
      //console.log(this.form.provincename);
      this.form.areaid = id
      this.increaseForm.areaname = this.form.areaname
      this.increaseForm.areaid = id
    },
    init(page, size){
      let that = this
      let user = this.formInline.user
      that
        .$axios({
          method:'get',
          url:'/warehouse/page',
          params:{
            page:page,
            rows:size,
            warehousename:user
          }
        })
        .then(({data})=> {
          for (let i = 0; i < data.records.length; i++){
            data.records[
              i
            ].createdate = common.timestampToTime(
              data.records[i].createdate
            )
            data.records[
              i
            ].modifydate = common.timestampToTime(
              data.records[i].modifydate
            )
          }

          that.tableData = data.records
          that.total = data.total
          that.pageSize = data.size
        })
    },

    //停用
    changeStatus2(index, row){
      let formdata = new FormData()
      formdata.append('status', 0)
      this.$axios({
        method:'put',
        url:`/warehouse/swt/${row.warehouseid}/0`,
        data:formdata
      }).then(()=> {
        this.tableData[index].status = 0
      })
    },

    //启用
    changeStatus1(index, row){
      let formdata = new FormData()
      formdata.append('status', 1)
      this.$axios({
        method:'put',
        url:`/warehouse/swt/${row.warehouseid}/1`,
        data:formdata
      }).then(()=> {
        this.tableData[index].status = 1
      })
    },
    setState(id){
      this.form.state = id
    },
    open(row){
      this.form.warehousename = row.warehousename
      this.form.state = row.state
      this.checkList = []
      this.form = JSON.parse(JSON.stringify(row))
      this.countryId = row.countryid
      this.provinceId = row.provinceid
      this.cityId = row.cityid
      this.initAddress(this.countryId)
      this.stateValue = row.state===1?this.$t('m.start'):this.$t('m.stop')
      this.dialogFormVisible = true
    },
    change(){
      this.$refs['ruleFormEdit'].validate(valid => {
        if (valid){
          this.$axios({
            method:'put',
            url:'/warehouse/update',
            data:this.form
          }).then(()=> {
            this.dialogFormVisible = false
            this.$message({
              showClose:true,
              message:this.$t('m.editSuccess'),
              type:'success',
              duration:1000
            })
            this.currentPage = 1
            this.init(1, this.pageSize)
          })
        }
      })
    },
    increase(){
      this.dialogFormVisible1 = true
    },
    handIncrease(){
      this.$refs['ruleFormAdd'].validate(valid => {
        if (valid){
          this.$axios({
            method:'post',
            url:'/warehouse/insert',
            data:this.increaseForm
          }).then(()=> {
            this.dialogFormVisible1 = false
            this.$message({
              showClose:true,
              message:this.$t('m.success'),
              type:'success',
              duration:1000
            })
            this.inCheckList = []
            this.init(1, this.pageSize)
          })
        }
      })
    },
    editCancel(){
      this.dialogFormVisible = false
      this.init(this.currentPage, this.pageSize)
    },
    closeDialog(){
      this.$refs['ruleFormEdit'].resetFields()
    },
    closeAddDialog(){
      this.$refs['ruleFormAdd'].resetFields()
    }
  },
  activated(){
    this.init(1, 10)
  },
  mounted(){
    this.$axios({
      method:'get',
      url:'/country/list'
    }).then(({data})=> {
      this.conuntryList = data
    })
  },
  beforeRouteLeave(to, form, next){
    this.dialogFormVisible=false
    this.dialogFormVisible1=false
    next()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style  lang="scss" scoped>
.mgb20{margin-bottom: 20px;}
.el-table td,
.el-table th.is-leaf {
  border-bottom: none;
}
</style>
